﻿(*
    The MIT License

    Copyright (c)2010 Fondevila Ltd

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in
    all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    THE SOFTWARE.
*)


namespace uk.co.fondevila.GoGo

module internal ClientLogin =

    open System.IO
    open System.Net
    open System.Text
    open System.Text.RegularExpressions

    open Exceptions

    let private clientLoginUrl = @"https://www.google.com/accounts/ClientLogin"
    let private postData = @"service={0}&continue=http://www.google.com/&Email={1}&Passwd={2}&source={3}"

    let private postRequest service email password source =
        let ascii = new ASCIIEncoding()
        let encodedPostData = 
            ascii.GetBytes(System.String.Format(postData, service, email, password, source))
        let request = HttpWebRequest.Create(clientLoginUrl) :?> HttpWebRequest

        request.Method <- "POST"
        request.ContentType <- "application/x-www-form-urlencoded"
        request.ContentLength <- int64(encodedPostData.Length)

        use newStream = request.GetRequestStream()
        newStream.Write(encodedPostData, 0, encodedPostData.Length);

        let mutable (response: HttpWebResponse) = null;
        try
            response <- request.GetResponse() :?> HttpWebResponse
        with
        | :? WebException as ex ->
            match ex.Response with
            | :? HttpWebResponse as faultResponse when faultResponse.StatusCode = HttpStatusCode.Forbidden ->
                raise (new IncorrectUsernameOrPasswordException(faultResponse.StatusCode, faultResponse.StatusDescription))
            | _ -> reraise()

        if response.StatusCode <> HttpStatusCode.OK then
            raise (new LoginFailedException(response.StatusCode, response.StatusDescription))

        use reader = new StreamReader(response.GetResponseStream())
        reader.ReadToEnd();
      

    let private parseAuthToken response =
        let mutable auth = ""

        try
            let regex = new Regex(@"Auth=(?<auth>\S+)")
            auth <- regex.Match(response).Result("${auth}")
        with
        | _ as ex ->
            raise(new AuthTokenException(ex.Message))

        if System.String.IsNullOrEmpty(auth) then
            raise(new AuthTokenException("Missing or invalid 'Auth' token."))

        auth



    let internal getAuthToken service username password source =
        let response = postRequest service username password source
        parseAuthToken response


